import { ElMessage } from "element-plus";

export const delay = (time = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
};

/**
 *
 * @param {Object} obj
 * @param {Function | undefined} checkFunc
 */
export const checkPropEmpty = (
  obj,
  checkDataEmpty = function (data) {
    if (data === "" || data === null || data === undefined) {
      return true;
    }
    return false;
  }
) => {
  for (const prop in obj) {
    if (Object.hasOwnProperty.call(obj, prop)) {
      if (typeof checkDataEmpty === "function" && checkDataEmpty(obj[prop])) {
        return false;
      }
    }
  }
  return true;
};

/**
 *
 * @param {Array} arr
 */
export const checkArrayPropEmpty = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    if (!checkPropEmpty(arr[i])) {
      return false;
    }
  }
  return true;
};

export const responseCallback = async function ({
  promise,
  cb = (data) => {},
  successMessage = "",
}) {
  const { code, msg, data } = await promise;
  if (code == 200) {
    if (successMessage) {
      ElMessage({
        message: successMessage,
        type: "success",
      });
    }

    cb && cb(data || true);
    return data || true;
  } else {
    ElMessage({
      message: msg,
      type: "warning",
    });
    return null;
  }
};

export const getFormData = (data) => {
  const formData = new FormData();
  for (const prop in data) {
    if (Object.hasOwnProperty.call(data, prop)) {
      formData.append(prop, data[prop]);
    }
  }
  return formData;
};
